package com.wdciti.sccp.iot.springvertx.protocols.tcp;

import com.wdciti.sccp.iot.springvertx.EndPointVerticle;
import com.wdciti.sccp.iot.springvertx.protocols.tcp.ext.FrameNetServerImpl;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.SocketAddress;
import lombok.extern.slf4j.Slf4j;

/**
 * @author by early
 */
@Slf4j
public class SimpleTcpServerVerticle extends EndPointVerticle {
    /*本来就是simple呀,要想实现复杂的NetServerOptions,比如SSL，还是自己去实现子类吧。*/
    private final NetServerOptions netServerOpt = new NetServerOptions();
    private NetServer netServer;
    private SocketAddress listenAddr;
    private boolean printHex;

    public SimpleTcpServerVerticle() {
    }

    public SimpleTcpServerVerticle(ByteToMessageDecoder decoder) {
        this.decoder = decoder;
    }

    @Override
    public void init(Vertx vertx, Context context) {
        super.init(vertx, context);
        String host = config().getString("host");
        int port = config().getInteger("port");
        this.printHex = config().getBoolean("printHex",false);
        this.listenAddr = SocketAddress.inetSocketAddress(port, host);
        this.netServerOpt.setHost(host).setPort(port);
        this.netServer = new FrameNetServerImpl((VertxInternal) vertx, netServerOpt, this.decoder);
    }

    @Override
    public void start() {
        Future<NetServer> future = netServer
                .connectHandler(new NetHandler(vertx.eventBus(), this.busAddr, this.codecName,this.printHex))
                .exceptionHandler(Throwable::printStackTrace)
                .listen(this.listenAddr);

        future.onComplete(fut -> {
            if (fut.succeeded()) {
                promiseReady();
            } else {
                fut.cause().printStackTrace();
            }
        });

    }

    @Override
    public void stop() {
        if (netServer != null) {
            netServer.close();
        }
    }

}
